#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.web.helper;

import ${package}.web.security.AuthUser;
import org.slf4j.MDC;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by well on 16/8/24.
 */
public class LogInterceptor extends HandlerInterceptorAdapter {

    private final static String LOG_USER_KEY = "log_user_key";
    private final static String remoteAddr = "remoteAddr";
    private final static String referrer = "referrer";
    private final static String userAgent = "userAgent";



    @Override
    public void afterCompletion(HttpServletRequest arg0,
                                HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
        MDC.remove(LOG_USER_KEY);
        MDC.remove(remoteAddr);
        MDC.remove(referrer);
        MDC.remove(userAgent);
    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
                           Object arg2, ModelAndView arg3) throws Exception {
    }

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {

        if(AuthUser.getCurrentUser()!=null && AuthUser.getCurrentUser().getUserId()!=null) {
            Long userId = AuthUser.getCurrentUser().getUserId();
            MDC.put(LOG_USER_KEY, String.valueOf(userId));

        }
        MDC.put(remoteAddr, request.getRemoteAddr());
        MDC.put(referrer, request.getHeader("Referer"));
        MDC.put(userAgent, request.getHeader("User-Agent"));

        return true;
    }
}
